package cn.leida.ruoyi.system.dao;

import cn.leida.ruoyi.common.core.domain.entity.SysRole;
import cn.leida.ruoyi.common.core.dto.SysRoleDto;
import cn.leida.ruoyi.system.dao.custom.SysMenuDaoCustom;
import com.alibaba.fastjson2.JSONObject;
import org.hibernate.query.sql.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色表 数据层
 *
 * @author liutietou
 * @since 1.0  2020-12-11
 */
@Repository
public interface SysRoleDao extends JpaRepository<SysRole, Long>, JpaSpecificationExecutor<SysRole>, SysMenuDaoCustom {

    public static final String baseSql = """
         select distinct r.role_id, r.role_name, r.role_key, r.role_sort,
        	r.data_scope, r.menu_check_strictly
        	, r.dept_check_strictly,r.status, r.del_flag, r.create_time,
        	r.create_by, r.update_by, r.update_time, r.remark
        from
        	sys_role r
        	left join sys_user_role ur on ur.role_id = r.role_id
        	left join sys_user u on u.user_id = ur.user_id
        	left join sys_dept d on u.dept_id = d.dept_id
        where
        	r.del_flag = '0'
        """;

    SysRole findByRoleId(Long roleId);

    @Query(value = """
        select  r.role_id  from sys_role r 
            left join sys_user_role ur on ur.role_id = r.role_id  
        	left join sys_user u on u.user_id = ur.user_id 
        where u.user_id = ?1 
        """, nativeQuery = true)
    List<Long> findRoleListByUserId(Long userId);

    List<SysRole> findByRoleName(String roleName);

    List<SysRole> findByRoleKey(String roleKey);

    void deleteByRoleId(Long roleId);

    void deleteByRoleIdIn(List<Long> roleId);

    @Query(value = baseSql + " and u.user_name = ?1 ", nativeQuery = true)
    List<SysRole> findRolesByUserName(String userName);

    List<SysRole> findByRoleIdIn(List<Long> roleIds);

    @Query(value = baseSql + " and u.user_id = ?1 ", nativeQuery = true)
    List<SysRole> findByUserIdAndDelFlag(Long userId);

    @Query(value = """
         select r.* from sys_role r 
         left join sys_user_role ur on ur.role_id = r.role_id
         left join sys_user u on u.user_id = ur.user_id 
         left join sys_dept d on u.dept_id = d.dept_id 
         WHERE r.del_flag = '0' and ur.user_id = ?1
        """, nativeQuery = true)
    public List<JSONObject> findRolePermissionByUserId(Long userId) ;
}
